package com.wkq.net.interceptor

import com.wkq.net.callback.FileDownCallback
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException
/**
 *
 *@Author: wkq
 *
 *@Time: 2025/4/15 11:57
 *
 *@Desc:文件下载进度
 */

class ProgressResponseBody(
    private val responseBody: ResponseBody,
    private val progressListener: FileDownCallback?=null
) : ResponseBody() {

    private var bufferedSource: BufferedSource? = null

    override fun contentType(): MediaType? = responseBody.contentType()

    override fun contentLength(): Long = responseBody.contentLength()

    override fun source(): BufferedSource {
        if (bufferedSource == null) {
            bufferedSource = source(responseBody.source()).buffer()
        }
        return bufferedSource!!
    }

    private fun source(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = 0L
            var curProgress = 0

            @Throws(IOException::class)
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                totalBytesRead += if (bytesRead != -1L) bytesRead else 0
                val progress = if (contentLength() > 0) {
                    (totalBytesRead * 100 / contentLength()).toInt()
                } else {
                    0
                }
                if ((progress%5) == 0&&curProgress!=progress) {
                    curProgress= progress
                    progressListener?.onProgress(curProgress)

                }

                return bytesRead
            }
        }
    }



}